<template>
	<view class="uni-view-compatible">
		<view class="uni-view-main">
			<!-- <view class="uni-view-shop">
				<view class="uni-view-shop-left">
					<image class="uni-view-shop-logo" v-if="shopInfo && shopInfo.logo" :src="shopInfo.logo"
						:mode="'scaleToFill'"></image>
					<image class="uni-view-shop-logo" v-else-if="reveal" :src="'/static/images/shop/empty_logo.png'"
						:mode="'scaleToFill'"></image>
				</view>
				<view class="uni-view-shop-right">
					<view class="uni-view-shop-item">
						<view class="uni-view-shop-name">
							{{ shopInfo && shopInfo.name ? shopInfo.name : '...查询中' }}
						</view>
					</view>
					<view class="uni-view-shop-item">
						<view class="uni-view-shop-btn" @tap="navToVoucher" v-if="reveal">
							{{ '领劵' }}
						</view>
						<view class="uni-view-shop-btn" @tap="navToRecharge" v-if="reveal">
							{{ '充值' }}
						</view>
					</view>
				</view>
			</view> -->

			<view class="uni-view-money">
				<view class="uni-view-money-background">
					<view class="uni-view-money-operate" v-if="balanceMoney">
						<checkbox-group @change="balanceChange">
							<checkbox value="balanceDeduction"></checkbox>
							<text
								class="uni-view-money-text">{{ '可用余额抵扣 ' + (parseFloat(balanceMoney) / 100).toFixed(2) + ' 元' }}</text>
						</checkbox-group>
					</view>

					<view class="uni-view-money-input">
						<text class="uni-view-money-input-prefix">
							{{ '¥ ' }}
						</text>
						<text
							:class="payMoney ? 'uni-view-money-input-suffix' : 'uni-view-money-input-suffix uni-view-money-input-placeholder'">
							{{ payText }}
						</text>
					</view>
				</view>
			</view>

			<view class="uni-view-keyboard">
				<keyboard ref="keyboard" :value="payMoney" :tips="tips" @keyInput="keyInput" @keyClear="keyClear"
					@keySure="keySure"></keyboard>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import keyboard from '../../../components/key-board/keyboard.vue';

	let _this;
	export default {
		components: {
			keyboard
		},
		data() {
			return {
				// spaceId: 'tcb-c3mmp92j9niy14x50ff63-22710f',
				appId: 'def1da4565222ccc05d977461539689c',
				shopId: 'def1da4565222ccc05d977461539689c',
				authCode: null,
				authPlatform: null,
				gatheringCode: null,
				shopInfo: null,
				user: null,
				member: null,
				placeholderStyle: 'font-family: \'NSimSun\',sans-serif; font-size: 32rpx;',
				balanceFlag: false,
				balanceMoney: null,
				payText: '请先输入支付金额',
				payMoney: null,
				tips: '确认支付',
				show: false,
				reveal: false
			};
		},
		onLoad(e) {
			_this = this;

			// #ifdef MP-ALIPAY
			const alipayExtJson = my.getExtConfigSync();
			if (alipayExtJson && alipayExtJson.appId) {
				_this.spaceId = alipayExtJson.spaceId;
				_this.appId = alipayExtJson.appId;
				_this.shopId = alipayExtJson.shopId;
			} else {
				let templateId = my.getAppIdSync().appId
				uni.setStorageSync("templateId", templateId)
			}
			// #endif

			// #ifdef MP-WEIXIN
			const wechatExtJson = uni.getExtConfigSync()
			if (wechatExtJson && wechatExtJson.appId) {
				_this.spaceId = wechatExtJson.spaceId;
				_this.appId = wechatExtJson.appId;
				_this.shopId = wechatExtJson.shopId;
			} else {
				const accountInfo = wx.getAccountInfoSync();
				uni.setStorageSync("templateId", accountInfo.miniProgram.appId)
			}
			// #endif

			if (e.shopId) {
				_this.shopId = e.shopId;
			}

			if (e.qrCode || e.q || uni.getStorageSync('qrCode')) {
				let scene = e.qrCode || e.q || uni.getStorageSync('qrCode');
				uni.setStorageSync('qrCode', scene);

				// #ifdef MP-WEIXIN
				scene = decodeURIComponent(scene);
				// #endif

				if (scene.indexOf("shopId") > -1) {
					_this.shopId = scene.split("shopId=")[1].split("&")[0];
				}
				if (scene.indexOf("gathering") > -1) {
					_this.gatheringCode = scene.split("gathering=")[1].split("&")[0];
				}
			}

			uni.setStorageSync('wmzmall_user_space_id', _this.spaceId);
			uni.setStorageSync('wmzmall_user_app_id', _this.appId);
			uni.setStorageSync('wmzmall_user_shop_id', _this.shopId);

			_this.getAuthCode();
		},
		onShow() {

		},
		onPullDownRefresh() {
			uni.stopPullDownRefresh();
		},
		methods: {
			...mapMutations(['login']),

			navToVoucher() {
				uni.navigateTo({
					url: '/pages/voucher/voucher'
				});
			},
			navToRecharge() {
				uni.navigateTo({
					url: '/sub-user/pages/wallet/wallet'
				});
			},
			getAuthCode() {
				// #ifdef MP-ALIPAY
				_this.authPlatform = 'alipay';

				uni.login({
					scopes: ['auth_base'],
					success(res) {
						if (res && res.code) {
							_this.authCode = res.code;
							_this.cloudLogin();
						} else {
							_this.$api.msg('获取支付宝授权码失败');
						}
					}
				});
				// #endif

				// #ifdef MP-WEIXIN
				_this.authPlatform = 'wechat';

				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success(res) {
						if (res && res.code) {
							_this.authCode = res.code;
							_this.cloudLogin();
						} else {
							_this.$api.msg('获取微信授权码失败');
						}
					}
				});
				// #endif
			},
			cloudLogin() {
				if (!_this.authCode) {
					_this.$api.msg('用户授权码参数丢失');
					return;
				}
				if (!_this.authPlatform) {
					_this.$api.msg('用户授权平台参数丢失');
					return;
				}

				let methodName;
				if ('alipay' === _this.authPlatform) {
					methodName = 'member/loginByAlipay';
				} else if ('wechat' === _this.authPlatform) {
					methodName = 'member/loginByWeixin';
				} else {
					_this.$api.msg('用户授权平台参数不正确');
					return;
				}

				let params = {
					app_id: _this.appId,
					code: _this.authCode,
					templateId: uni.getStorageSync("templateId")
				};

				_this.$func.wmzmall.call(methodName, params).then(res => {
					if (res && res.code && 200 === res.code && res.datas) {
						_this.login(res.datas);
						// _this.loadShopInfo();

						if (res.datas.user) {
							_this.user = res.datas.user;
						}
						if (res.datas.member) {
							_this.member = res.datas.member;
							if (_this.member.member_amount) {
								_this.balanceMoney = _this.member.member_amount;
							}
						}
					} else if (res.msg) {
						_this.$api.msg(res.msg);
					} else {
						_this.$api.msg('用户授权登录失败');
					}
				}).catch(err => {
					console.log(err);
				});
			},
			loadShopInfo() {
				_this.$func.wmzmall.call('shop/getShopInfoById', {
					shop_id: _this.shopId
				}).then(res => {
					if (res && res.code && 200 === res.code && res.datas && res.datas.data) {
						_this.shopInfo = res.datas.data;
					} else if (res.msg) {
						_this.$api.msg(res.msg);
					} else {
						_this.$api.msg('获取门店信息数据失败');
					}
				}).catch(err => {
					console.log(err);
				});
			},
			balanceChange(e) {
				let changeValue = false;

				if (e && e.detail && e.detail.value && e.detail.value.length > 0) {
					if (e.detail.value.indexOf('balanceDeduction') > -1) {
						changeValue = true;
					}
				}

				_this.balanceFlag = changeValue;
			},
			keyInput(val) {
				if (val) {
					_this.payMoney = val;
				} else {
					_this.payMoney = null;
				}

				if (_this.payMoney) {
					_this.payText = _this.payMoney;
				} else {
					_this.payText = '请先输入支付金额';
				}
			},
			keyClear() {
				_this.payMoney = null;
				_this.payText = '请先输入支付金额';
			},
			keySure() {
				if (!_this.payMoney) {
					_this.$api.msg('请先输入支付金额');
					return;
				}
				/* 
								let canUseBalance = false;

								if (_this.balanceFlag) {
									if (!_this.balanceMoney) {
										_this.$api.msg('您暂无余额可以抵扣');
										return;
									}
									if (parseFloat(_this.payMoney) > parseFloat(_this.balanceMoney)) {
										_this.$api.msg('您当前余额不足，不够抵扣支付金额');
										return;
									}
									canUseBalance = true;
								} */

				let payWay;
				if ('alipay' === _this.authPlatform) {
					payWay = '支付宝';
				} else if ('wechat' === _this.authPlatform) {
					payWay = '微信支付';
				} else if (canUseBalance) {
					payWay = '余额支付';
				} else {
					_this.$api.msg('您当前余额不足，不够抵扣支付金额');
					return;
				}

				let params = {
					appId: _this.appId,
					shopId: _this.shopId,
					authCode: _this.authCode,
					authPlatform: _this.authPlatform,
					payWay: payWay,
					payMoney: _this.payMoney
				};

				_this.$func.wmzmall.call('gathering/orderPay', params).then(res => {
					if (res && res.code && 200 === res.code && res.datas && res.datas.data) {
						let data = res.datas.data;
						let payOrderInfo = null;

						// #ifdef MP-ALIPAY
						payOrderInfo = {
							tradeNO: data.trade_no
						};
						// #endif

						//#ifdef MP-WEIXIN
						payOrderInfo = {
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign
						};
						//#endif

						if (!payOrderInfo) {
							_this.$api.msg('仅支持支付宝、微信小程序支付');
							return;
						}

						uni.requestPayment({
							...payOrderInfo,
							success: (paySuccess) => {
								console.log('requestPayment success:', paySuccess);

								let url = '/pages/gathering/result/result?payMoney=' + _this.payMoney +
									'&payWay=' + payWay;

								// #ifdef MP-ALIPAY
								if (paySuccess && paySuccess.resultCode && 9000 === parseInt(paySuccess
										.resultCode)) {
									uni.navigateTo({
										url: url
									});
								} else if (paySuccess && paySuccess.memo) {
									_this.$api.msg(paySuccess.memo);
								} else {
									_this.$api.msg('支付未完成，请重新支付');
								}
								// #endif

								//#ifdef MP-WEIXIN
								uni.navigateTo({
									url: url
								});
								//#endif
							},
							fail: (payError) => {
								console.log('requestPayment fail:', payError);
							}
						});
					} else if (res.msg) {
						_this.$api.msg(res.msg);
					} else {
						_this.$api.msg('收款码下单支付失败');
					}
				}).catch(err => {
					console.log(err);
				});
			}
		}
	};
</script>

<style lang="scss">
	@import '~@/pages/gathering/pay/pay.scss';
</style>